# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

import pymongo
from urllib.parse import quote_plus
import time
import hashlib


# 替换字段中指定字符
class ReplaceItemPipeline(object):

    def process_item(self, item, spider):
        if item['source'] is not None:
            item['source'] = item['source'].replace("来源", "").replace("\n\r", "")
        return item


# 去除字段中的空格信息
class TrimProjectPipeline(object):

    def process_item(self, item, spider):
        data = dict(item)
        for key in data:
            if data[key] is not None and isinstance(data[key], str):
                item[key] = data[key].strip()
        return item


# 生成唯一标识
class IdentifyPipeline(object):

    def process_item(self, item, spider):
        md5 = hashlib.md5()
        md5.update(item['title'].encode(encoding='utf-8'))
        item['identify'] = md5.hexdigest()
        return item


# 存储数据
class MongodbPipeline(object):

    collection_name = 'news_ce'

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get("MONGO_URI") % (quote_plus(crawler.settings.get("MONGO_PASSWORD"))),
            mongo_db=crawler.settings.get("MONGO_DATABASE", "scrapy")
        )

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        item['c_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        try:
            self.db[self.collection_name].insert_one(dict(item))
        except Exception as e:
            spider.logger.warn(e.msg)

        return item
